package com.car.util;

import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author 党怡承
 * @since 2021-08-09
 * @description http工具类
 */
@Component
public class HttpUtil {

  public static String post(String requestUrl, String accessToken, String params) throws Exception {
    String contentType = "application/x-www-form-urlencoded";
    return HttpUtil.post(requestUrl, accessToken, contentType, params);
  }

  public static String post(
      String requestUrl, String accessToken, String contentType, String params) throws Exception {
    String encoding = "UTF-8";
    if (requestUrl.contains("nlp")) {
      encoding = "GBK";
    }
    return HttpUtil.post(requestUrl, accessToken, contentType, params, encoding);
  }

  public static String post(
      String requestUrl, String accessToken, String contentType, String params, String encoding)
      throws Exception {
    String url = requestUrl + "?access_token=" + accessToken;
    return HttpUtil.postGeneralUrl(url, contentType, params, encoding);
  }

  public static String postGeneralUrl(
      String generalUrl, String contentType, String params, String encoding) throws Exception {
    BufferedReader in = null;
    DataOutputStream out = null;
    try {
      URL url = new URL(generalUrl);
      HttpURLConnection connection = (HttpURLConnection) url.openConnection();
      connection.setRequestMethod("POST");
      connection.setRequestProperty("Content-Type", contentType);
      connection.setRequestProperty("Connection", "Keep-Alive");
      connection.setUseCaches(false);
      connection.setDoOutput(true);
      connection.setDoInput(true);
      out = new DataOutputStream(connection.getOutputStream());
      out.write(params.getBytes(encoding));
      in = new BufferedReader(new InputStreamReader(connection.getInputStream(), encoding));
      StringBuffer result = new StringBuffer();
      String getLine;
      while ((getLine = in.readLine()) != null) {
        result.append(getLine);
      }
      return result.toString();
    } catch (Exception e) {
      throw new RuntimeException(e.getMessage());
    } finally {
      if (in != null && out != null) {
        out.flush();
        out.close();
        in.close();
      }
    }
  }
}
